Grokking SQL for Tech Interviews
Rate this course
Ask Author
Contribute
Back to course home

1% completed

Vote For New Content
Introduction
Course Overview
What is RDBMS?
What is SQL?
A Quick Review of SQL
Read data from table
WHERE Clause
Operators
Handle NULLs in SQL
DISTINCT Clause
ORDER BY Clause
LIMIT and OFFSET
GROUP BY
HAVING
Aggregate Functions
Order of Execution
Order of SQL Query Execution
SQL Functions
Number Functions
String Functions
Date Functions
Nested Queries
Nested Query
Types of Subqueries
JOINS
Introduction
INNER JOIN
LEFT OUTER JOIN
RIGHT OUTER JOIN
FULL OUTER JOIN
SELF JOIN
SET Operations
What are SET operations?
UNION
INTERSECT
EXCEPT
A Quick Review of DDL
Keys in SQL
CREATE
ALTER
DROP
TRUNCATE
Indexes
A Quick Review of DML
INSERT
UPDATE
DELETE
Database Backup & Restore
Backup Database
Restore Database
Interview Problems - Easy
1. Major Cities
2. Not boring movies
3. Triangle Judgement
4. Biggest Single Number
5. Product Sales Analysis I
6. Product Sales Analysis II
7. Game Play Analysis I
8. Game Play Analysis II
9. Queries Quality and Percentage
10. Average Selling Price
11. Weather Type in Each Country
12. Students and Examinations
13. Ads Performance
14. Group Sold Products By The Date
15. Employee Email Verification
16. Sellers With No Sales
17. Average Time of Process
18. Find Followers Count
19. Ad-Free Sessions
20. Bikes Last Time Used
21. Daily User Engagement Levels
22. Employee Attendance Record
23. Library Book Loans
24. Customer Purchase Summary
25. Long Comments (Easy)
26. Unused Accounts
27. Patient Appointment No-Shows
28. Books and Authors
29. High School Attendance
30. Employee Absences
31. Green Product Identification (Easy)
32. Employee Department Exclusion (Easy)
33. Sales Person (Easy)
34. Employee Task Tracking (Easy)
Interview Problems - Medium
1. Winning Candidate
2. Second Degree Follower
3. 2nd Highest Salary
4. Game Play Analysis III
5. Game Play Analysis IV
6. Active Businesses
7. Product Price on a Specific Date
8. Monthly Transactions II
9. Team Scores in Football Tournament
10. Page Recommendations
11. Running Total for Different Genders
12. Evaluate Boolean Expression
13. Active Users
14. Find Interview Candidates
15. Suspicious Bank Accounts
16. Order Fulfillment Rate (Medium)
17. Last Person to Fit in the Elevator (Medium)
18. Retail Expansion Analysis (Medium)
19. Employee Collaboration Networks (Medium)
20. Second Fastest Time in Races (Medium)
Interview Problems - Hard
1. Trips and Users
2. Human Traffic of Stadium
3. Students Report By Geography
4. Game Play Analysis V
5. Number of Transactions per Visit
6. Find the Quiet Students in All Exams
7. First and Last Call On the Same Day
8. Build the Equation
9. Longest Winning Streak
10. Dynamic Pivoting of a Table
11. Dynamic Unpivoting of a Table
12. Generate the Invoice
13. Popularity Percentage
14. Viewers Turned Streamers
15. Status of Flight Tickets
1. High Performing Employees (Easy)
2. Student Course Averages (Easy)
3. Library Book Checkout Percentage (Easy)
4. Employee Performance and Improvement Rate (Easy)
5. Find Popular Posts (Easy)
6. Main Office Assignment for Each Employee (Easy)
7. Rectangle Validation (Easy)
8. Library Book Checkouts by Date (Easy)
9. Same-Day Appointment Fulfillment (Medium)
10. Departments with High Earning Employees (Medium)
11. Students Who Attended All Courses (Medium)
12. Library Book Checkouts First Year (Medium)
13. Repeated Values in Sequence (Medium)
14. School Top Achievers by Subject (Hard)
14. Viewers Turned Streamers

Problem

Table: Sessions

+---------------+----------+
| Column Name   | Type     |
+---------------+----------+
| user_id       | int      |
| session_start | datetime |
| session_end   | datetime |
| session_id    | int      |
| session_type  | enum     |
+---------------+----------+
session_id is column of unique values for this table.
session_type is an ENUM (category) type of (Viewer, Streamer).
This table contains user id, session start, session end, session id and session type.

Problem Definition

Write a solution to find the number of streaming sessions for users whose first session was as a viewer.

Return the result table ordered by count of streaming sessions, user_id in descending order.

Example

Image

Output

Image

Try It Yourself

MYSQL

. . . .

Sessions =

Solution

To identify the number of streaming sessions for users whose first session was as a viewer, we analyze the Sessions table. We can efficiently accomplishes this by leveraging Common Table Expressions (CTEs), window functions, and conditional aggregations. Below is a comprehensive breakdown of the approach, step-by-step execution, and detailed explanations for each line of the SQL query.

Approach Overview

  1. Determine the First Session of Each User:

    • Use a window function to rank sessions based on the session_start time for each user.
    • Identify users whose first session (rank = 1) was as a viewer.
  2. Count Streaming Sessions for Qualified Users:

    • For users identified in the first step, count the number of sessions where session_type is Streamer.
  3. Filter and Order the Results:

    • Ensure that only users who have both Viewer and Streamer session types are considered.
    • Order the final results by the count of streaming sessions in descending order and by user_id in descending order in case of ties.

SQL Query

WITH cte AS ( SELECT user_id, session_type, RANK() OVER ( PARTITION BY user_id ORDER BY session_start ) AS rnk FROM Sessions ) SELECT user_id, SUM(CASE WHEN session_type = 'Streamer' THEN 1 ELSE 0 END) AS sessions_count FROM Sessions WHERE user_id IN ( SELECT user_id FROM cte WHERE rnk = 1 AND session_type = 'Viewer' ) GROUP BY user_id HAVING COUNT(DISTINCT session_type) = 2 ORDER BY sessions_count DESC, user_id DESC;

Step-by-Step Approach

Step 1: Determine the First Session of Each User (cte)

Identify the first session (rnk = 1) of each user to determine if it was a viewer session.

SQL Snippet:

WITH cte AS ( SELECT user_id, session_type, RANK() OVER ( PARTITION BY user_id ORDER BY session_start ) AS rnk FROM Sessions )

Explanation:

  1. WITH cte AS (

    • Initiates a Common Table Expression (CTE) named cte. CTEs are temporary result sets that can be referenced within the main query.
  2. SELECT user_id, session_type,

    • Selects the user_id and session_type columns from the Sessions table.
  3. RANK() OVER (

    • Applies the RANK() window function to assign a rank to each session based on the session_start time.
  4. PARTITION BY user_id

    • Divides the data into partitions for each user_id. The ranking will reset for each user.
  5. ORDER BY session_start

    • Orders the sessions within each partition by the session_start datetime in ascending order. The earliest session gets the highest priority.

Intermediate Output After Step 1 (cte):

+---------+--------------+-----+ | user_id | session_type | rnk | +---------+--------------+-----+ | 101 | Viewer | 1 | | 101 | Streamer | 2 | | 101 | Streamer | 3 | | 101 | Streamer | 4 | | 102 | Lose | 1 | | 102 | Lose | 2 | | 103 | Streamer | 1 | | 104 | Viewer | 1 | +---------+--------------+-----+

Step 2: Identify Users Whose First Session Was as a Viewer

Select users whose first session (rnk = 1) was as a viewer.

SQL Snippet:

SELECT user_id FROM cte WHERE rnk = 1 AND session_type = 'Viewer'

Explanation:

  1. SELECT user_id

    • Selects the user_id from the cte.
  2. FROM cte

    • Specifies the CTE cte as the data source.
  3. WHERE rnk = 1 AND session_type = 'Viewer'

    • Filters the records to include only those where the rank is 1 (first session) and the session type is 'Viewer'.

Intermediate Output After Step 2:

+---------+ | user_id | +---------+ | 101 | | 104 | +---------+

Step 3: Count Streaming Sessions for Qualified Users

For the users identified in the previous step (whose first session was as a Viewer), count the number of sessions where session_type is Streamer.

SQL Snippet:

SELECT user_id, SUM(CASE WHEN session_type = 'Streamer' THEN 1 ELSE 0 END) AS sessions_count FROM Sessions WHERE user_id IN ( SELECT user_id FROM cte WHERE rnk = 1 AND session_type = 'Viewer' ) GROUP BY user_id HAVING COUNT(DISTINCT session_type) = 2 ORDER BY sessions_count DESC, user_id DESC;

Explanation:

  1. SELECT user_id,

    • Selects the user_id from the Sessions table.
  2. SUM(CASE WHEN session_type = 'Streamer' THEN 1 ELSE 0 END) AS sessions_count

    • Uses a CASE statement to assign 1 for Streamer sessions and 0 otherwise.
    • Sums these values to count the total number of Streamer sessions for each user.
    • Aliases the sum as sessions_count.
  3. Subquery:

    SELECT user_id FROM cte WHERE rnk = 1 AND session_type = 'Viewer'
    • As explained in Step 2, selects users whose first session was as a Viewer.
  4. GROUP BY user_id

    • Groups the data by user_id to perform the aggregation for each user.
  5. HAVING COUNT(DISTINCT session_type) = 2

    • Ensures that only users who have both Viewer and Streamer sessions are included.
    • This condition filters out users who have only Viewer or only Streamer sessions.
  6. ORDER BY sessions_count DESC, user_id DESC;

    • Orders the final results first by the count of streaming sessions in descending order.
    • In case of ties, orders by user_id in descending order.

Final Output:

+---------+----------------+ | user_id | sessions_count | +---------+----------------+ | 101 | 2 | +---------+----------------+
13. Popularity Percentage
15. Status of Flight Tickets
Mark as Completed

On this page

Problem

Problem Definition

Example

Output

Try It Yourself

Solution

Approach Overview

SQL Query

Step-by-Step Approach